'''
@Project ：dataProcessing.py 
@File    ：PredictWindow.py
@IDE     ：PyCharm 
@Author  ：子协
@Date    ：2025-04-02 11:28 
'''
from PyQt5.QtWidgets import QWidget, QPushButton,QLabel,QDesktopWidget
from PyQt5.QtCore import Qt,QTimer, pyqtSignal, QRect
from PyQt5.QtGui import QColor, QFont, QPainter, QPen,QPixmap
import numpy as np

Label_Height = 200  # 标签的大小（高）
Label_Width = 250   #标签的大小（宽）
Button_Height = 80  #按钮的大小（高）
Button_Width = 100  #按钮的大小（宽）

Margin_Top = 100     # 上边距 100
Margin_Down = 100    # 下边距 100
Margin_Left = 100   # 左边距 100
Margin_Right = 100  # 右边距 100

MAX_TIMES = 5       # 倒计时时长

def StyleChange(LabelList,LabelLen,state,ColorList):
    mask = 0b00000011
    for i in range(0,LabelLen):
        index = (state >> (6 - 2 * i)) & mask
        LabelList[i].setStyleSheet(
            f"QLabel {{"
            f"font-size: 24px; "
            f"border: 2px solid black; "
            f"background-color: {ColorList[index]}; "
            f"border-top-left-radius: 10px; "
            f"border-top-right-radius: 10px; "
            f"border-bottom-left-radius: 10px; "
            f"border-bottom-right-radius: 10px; "
            f"}}"
        )


#数据采集窗口
class PredictWindow(QWidget):
    predictSignal = pyqtSignal(int)       # 向主窗口传递信号  最高位为0：开始采集信号  最高位为1：当前状态信号
    # bit7          bit6    bit5 bit4 bit3 bit2 bit1 bit0
    # 状态          类型            数据
    # 0:结束采集    0:正常数据      数据
    # 1:开始采集    1:基准数据      数据
    # 00_   结束采集正常数据        0x00
    # 01_   结束采集基准数据        0x40
    # 10_   开始采集正常数据        0x80
    # 11_   开始采集基准数据        0xC0

    def __init__(self):
        super().__init__()

        self.setStyleSheet("background-color: black;")                  # 设置界面背景色或其他组件
        self.setWindowTitle("FetchData Window")
        self.setFocusPolicy(Qt.StrongFocus)
        self.setFocus()
        screen = QDesktopWidget().screenGeometry()
        self.screen_width = screen.width()
        self.screen_height = screen.height()

        self.button_Begin = QPushButton(self)
        self.label_Up = QLabel(self)
        self.label_Down = QLabel(self)
        self.label_Left = QLabel(self)
        self.label_Right = QLabel(self)
        self.timer_NormalData = QTimer(self)
        self.timer_NormalData.setInterval(10)
        self.timer_NormalData.stop()
        self.timer_BasicData = QTimer(self)  # 基线数据定时器
        self.timer_BasicData.setInterval(1000)  # 定时1S
        self.timer_BasicData.stop()

        self.ColorState = 0b11000000  # 标签颜色的变化
        self.FetchDataIsRunning = False     # 数据采集是否运行
        self.FetchDataIsOK = False          # 数据采集是否完成
        self.BasicDataIsOK = False  # 基线数据是否采集完成
        self.BasicDataTimes = MAX_TIMES  # 基线数据定时器定时时长
        self.ColorIndex = 0

        self.button_Begin.clicked.connect(self.Callback_BeginButtonClicked)
        self.timer_NormalData.timeout.connect(self.Callback_TimeOut_NormalData)
        self.timer_BasicData.timeout.connect(self.Callback_TimeOut_BasicData)

        self.LayoutInit()
        self.showFullScreen()  # 设置全屏

    def keyPressEvent(self, event):
        # 检测是否按下了Esc键
        if event.key() == Qt.Key_Escape:
            self.close()
        elif event.key() == Qt.Key_Space:   # 空格
            self.button_Begin.click()
        else:
            super().keyPressEvent(event)

    def paintEvent(self, event):
        if self.BasicDataIsOK:
            return
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)    # 启用抗锯齿，使圆形更加平滑
        rect = self.rect()
        center = rect.center()
        radius = 150                                    # 圆的半径
        circle_rect = QRect(center.x() - radius, center.y() - radius, 2 * radius, 2 * radius)  # 设置圆形的尺寸和位置

        painter.setBrush(QColor(220, 220, 220, 150))    # 灰色半透明背景
        painter.setPen(Qt.NoPen)                        # 无边框
        painter.drawEllipse(circle_rect)                # 绘制圆形

        font = QFont("Arial", 40, QFont.Bold)           # 设置字体
        painter.setFont(font)
        painter.setPen(QPen(QColor(255, 255, 255, 255)))# 白色字体

        text = str(self.BasicDataTimes)                 # 获取倒计时的文本
        text_rect = painter.boundingRect(circle_rect, Qt.AlignCenter, text) # 计算文本的矩形区域，使其居中

        painter.drawText(text_rect, Qt.AlignCenter, text)  # 绘制倒计时数字

        painter.end()
    # 预测完成，显示预测标签，停止采集，关闭定时器
    def ShowLabel(self,predict_label):
        Label_list = [self.label_Up, self.label_Right, self.label_Down, self.label_Left]       # pyqt标签列表
        ColorList = ["white","#FFB5C5"]                                                         # 标签颜色列表
        self.timer_NormalData.stop()
        self.FetchDataIsRunning = False
        self.label_Up.setStyleSheet(
            "QLabel { font-size: 24px;border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")
        self.label_Down.setStyleSheet(
            "QLabel {font-size: 24px; border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")
        self.label_Left.setStyleSheet(
            "QLabel { font-size: 24px;border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")
        self.label_Right.setStyleSheet(
            "QLabel { font-size: 24px; border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")
        self.label_Up.move(self.label_Up_StartX, self.label_Up_StartY)
        self.label_Down.move(self.label_Down_StartX, self.label_Down_StartY)
        self.label_Left.move(self.label_Left_StartX, self.label_Left_StartY)
        self.label_Right.move(self.label_Right_StartX, self.label_Right_StartY)
        self.ColorChange(Label_list[predict_label-1],1,ColorList)

    # 开始按钮回调函数
    def Callback_BeginButtonClicked(self):
        if not self.BasicDataIsOK:                      # 如果还没开始采集基准数据则开始采集基准数据
            byte = 0xC0                                 # 0b1100_0000 开始采集基准数据
            self.timer_BasicData.start()                # 开始采集基准数据
            self.predictSignal.emit(byte)
        else:                                           # 基准数据已经采集完成开始采集正常数据
            byte = 0x80                                 # 开始采集正常数据(解挂串口接收线程)
            self.predictSignal.emit(byte)
            self.timer_NormalData.start()

    def Callback_TimeOut_NormalData(self):
        ColorList = ["black", "#828282"]
        self.ColorChange(self.label_Up, self.ColorIndex, ColorList)
        self.ColorChange(self.label_Down, self.ColorIndex, ColorList)
        self.ColorChange(self.label_Left, self.ColorIndex, ColorList)
        self.ColorChange(self.label_Right, self.ColorIndex, ColorList)
        self.LocationChange(1, 1)
        self.LocationChange(1, 2)
        self.LocationChange(1, 3)
        self.LocationChange(1, 4)
        self.ColorIndex ^= 1

    def Callback_TimeOut_BasicData(self):
        self.BasicDataTimes -= 1
        if self.BasicDataTimes <= 0:                # 已采集MAX_TIMES基准数据，基准数据已采集完成，开始采集正常数据
            self.timer_BasicData.stop()
            self.BasicDataTimes = MAX_TIMES         # 重置倒计时时长为MAX_TIMES
            byte = 0x40                             # 结束采集基准数据(暂停串口接收线程)
            self.predictSignal.emit(byte)
            byte = 0x80                             # 开始采集正常数据(解挂串口接收线程)
            self.predictSignal.emit(byte)
            self.FetchDataIsRunning = True
            self.BasicDataIsOK = True          # 倒计时结束
            self.timer_NormalData.start()
        self.update()                               # 重绘窗口

    def ColorChange(self,Label, ColorIndex, ColorList):
        Label.setStyleSheet(
            f"QLabel {{"
            f"font-size: 24px; "
            f"border: 2px solid black; "
            f"background-color: {ColorList[ColorIndex]}; "
            f"border-top-left-radius: 10px; "
            f"border-top-right-radius: 10px; "
            f"border-bottom-left-radius: 10px; "
            f"border-bottom-right-radius: 10px; "
            f"}}"
        )

    def LocationChange(self,step,direction):
        if direction == 1:
            curX = self.label_Up.geometry().x()
            curY = self.label_Up.geometry().y()
            nextX = self.label_Up_StartX
            nextY = curY - step
            if nextY == self.label_Up_StopY:
                nextY = self.label_Up_StartY
            self.label_Up.move(nextX,nextY)
        elif direction == 2:
            curX = self.label_Right.geometry().x()
            curY = self.label_Right.geometry().y()
            nextX = curX + step
            nextY = self.label_Right_StartY
            if nextX == self.label_Right_StopX:
                nextX = self.label_Right_StartX
            self.label_Right.move(nextX, nextY)
        elif direction == 3:
            curX = self.label_Down.geometry().x()
            curY = self.label_Down.geometry().y()
            nextX = self.label_Down_StartX
            nextY = curY + step
            if nextY == self.label_Down_StopY:
                nextY = self.label_Down_StartY
            self.label_Down.move(nextX, nextY)
        elif direction == 4:
            curX = self.label_Left.geometry().x()
            curY = self.label_Left.geometry().y()
            nextX = curX - step
            nextY = self.label_Left_StartY
            if nextX == self.label_Left_StopX:
                nextX = self.label_Left_StartX
            self.label_Left.move(nextX, nextY)

    def LayoutInit(self):
        self.label_Up.setPixmap(QPixmap(r"./images/up.png"))
        self.label_Down.setPixmap(QPixmap(r"./images/down.png"))
        self.label_Left.setPixmap(QPixmap(r"./images/left.png"))
        self.label_Right.setPixmap(QPixmap(r"./images/right.png"))

        self.label_Up.resize(Label_Width, Label_Height)
        self.label_Down.resize(Label_Width, Label_Height)
        self.label_Left.resize(Label_Width, Label_Height)
        self.label_Right.resize(Label_Width, Label_Height)

        self.label_Up_StartX = self.screen_width // 2 - Label_Width // 2
        self.label_Up_StartY = Margin_Top
        self.label_Down_StartX = self.screen_width // 2 - Label_Width // 2
        self.label_Down_StartY = self.screen_height - Margin_Down - Label_Height
        self.label_Left_StartX = Margin_Left
        self.label_Left_StartY = self.screen_height // 2 - Label_Height // 2
        self.label_Right_StartX = self.screen_width - Margin_Right - Label_Width
        self.label_Right_StartY = self.screen_height // 2 - Label_Height // 2

        self.label_Up_StopX = self.screen_width // 2 - Label_Width // 2
        self.label_Up_StopY = 0
        self.label_Down_StopX = self.screen_width // 2 - Label_Width // 2
        self.label_Down_StopY = self.screen_height - Label_Height
        self.label_Left_StopX = 0
        self.label_Left_StopY = self.screen_width // 2 - Label_Width // 2
        self.label_Right_StopX = self.screen_width - Label_Width
        self.label_Right_StopY = self.screen_height // 2 - Label_Height // 2

        self.label_Up.move(self.label_Up_StartX, self.label_Up_StartY)
        self.label_Down.move(self.label_Down_StartX, self.label_Down_StartY)
        self.label_Left.move(self.label_Left_StartX, self.label_Left_StartY)
        self.label_Right.move(self.label_Right_StartX, self.label_Right_StartY)

        self.label_Up.setStyleSheet(
            "QLabel { font-size: 24px;border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")
        self.label_Down.setStyleSheet(
            "QLabel {font-size: 24px; border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")
        self.label_Left.setStyleSheet(
            "QLabel { font-size: 24px;border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")
        self.label_Right.setStyleSheet(
            "QLabel { font-size: 24px; border: 2px solid black; background-color: white;border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px; }")

        self.label_Up.setAlignment(Qt.AlignCenter)
        self.label_Down.setAlignment(Qt.AlignCenter)
        self.label_Left.setAlignment(Qt.AlignCenter)
        self.label_Right.setAlignment(Qt.AlignCenter)
        self.button_Begin.setVisible(False)